package org.bizming.medicine.service;

import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.bizming.base.BaseErrCode;
import org.bizming.base.BaseException;
import org.bizming.medicine.dao.MedicineDao;
import org.bizming.medicine.dao.PurChaseDao;
import org.bizming.medicine.model.Medicine;
import org.bizming.medicine.model.PurChaseMedicine;
import org.bizming.medicine.model.ext.PurChaseExt;
import org.bizming.medicine.model.help.ActionType;
import org.bizming.web.util.Helper;

public class PurchaseServiceImpl implements PurchaseService {

	private PurChaseDao purChaseDao;

	private MedicineDao medicineDao;

	@Override
	public boolean add(PurChaseExt ext) throws Exception {
		if (ext == null || !Helper.validate(ext.getMedicine(), ActionType.ADD)
				|| !Helper.validate(ext, ActionType.ADD)) {
			throw new BaseException(BaseErrCode.INVALIDATE);
		}
		int id = medicineDao.add(ext.getMedicine());
		ext.setMedicineId(id);

		PurChaseMedicine t = new PurChaseMedicine();
		BeanUtils.copyProperties(t, ext);
		purChaseDao.add(t);

		return true;
	}

	@Override
	public List<PurChaseExt> selectList() {
		List<PurChaseExt> list = purChaseDao.selectList();
		if (!Helper.isEmpty(list)) {
			Medicine medicine;
			for (PurChaseExt t : list) {
				medicine = medicineDao.get(t.getMedicineId());
				t.setMedicine(medicine);
			}
		}
		return list;
	}

	@Override
	public PurChaseExt get(int id) {
		PurChaseExt t = purChaseDao.get(id);
		if (t != null) {
			Medicine medicine = medicineDao.get(t.getMedicineId());
			t.setMedicine(medicine);
			return t;
		}
		return null;
	}

	@Override
	public int count() {
		return purChaseDao.count();
	}

	@Override
	public void remove(int id) {
		PurChaseExt t = purChaseDao.get(id);
		if (t != null) {
			medicineDao.remove(t.getMedicineId());
			purChaseDao.remove(id);
		}
	}

	// ===============================

	public PurChaseDao getPurChaseDao() {
		return purChaseDao;
	}

	public void setPurChaseDao(PurChaseDao purChaseDao) {
		this.purChaseDao = purChaseDao;
	}

	public MedicineDao getMedicineDao() {
		return medicineDao;
	}

	public void setMedicineDao(MedicineDao medicineDao) {
		this.medicineDao = medicineDao;
	}
}
